import json
import requests
from flask import request, jsonify, make_response
from app import app
from copy import deepcopy
from service.calculateInfluence import calculate_pr
from service.AnomalyDetection import consAnomalousService
from service.constructAnomalyChain import consAnomalyChain
from service.calRank import calTopK

result_response = {'code': 0, 'message': 'success', 'data': None}

graph_data = {}

res_graph = {}

init_flag = True

anomalous_services = []

metric_map = {
    'ResponseTime': 100014,
    'ErrorCount': 100015,
    'QueryPerSecond': 100016
}

metric_map_1 = {
    100014: 'ResponseTime',
    100015: 'ErrorCount',
    100016: 'QueryPerSecond'
}


@app.route('/getMetricsDiagnose', methods=['GET', 'POST'])
def getMetricsDiagnose():
    response = deepcopy(result_response)
    try:
        global graph_data
        global res_graph
        global anomalous_services
        global init_flag
        if init_flag:
            graph_data = requests.post(url='http://119.29.92.219:8090/serviceTopo').text
            init_flag = False
            graph_data = json.loads(graph_data)
            nodes = graph_data['nodes']
            edges = graph_data['edges']
            for node in nodes:
                node['status'] = 1 if node['status'] > 0 else 0
            for edge in edges:
                edge.pop('status')
            res_graph = calculate_pr(graph_data)
            anomalous_services = [node for node in nodes if node['status'] != 0]
            anomalous_services = consAnomalousService(anomalous_services)
            res_graph = calTopK(res_graph, anomalous_services, 1)
        response['data'] = res_graph
    except Exception as e:
        response['code'] = 1
        response['message'] = str(e)
    res = make_response(jsonify(response))  # 设置响应体
    res.headers['Access-Control-Allow-Origin'] = "*"  # 设置允许跨域
    res.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    return res


@app.route('/getAnomalousMetrics', methods=['GET', 'POST'])
def getAnomalousMetrics():
    response = deepcopy(result_response)
    try:
        service_ids = json.loads(request.data).get('service_ids')
        level = json.loads(request.data).get('level')
        exception_categories = anomalous_services.copy()
        if service_ids and len(service_ids) > 0:
            exception_categories = [item for item in exception_categories if item['id'] in service_ids]
        if level and len(level) > 0:
            exception_categories = [item for item in exception_categories if item['level'] in level]
        exception_metrics = []
        for item in exception_categories:
            for metric in item['anomalous_metrics']:
                log = item.copy()
                log['service_id'] = item['id']
                log['id'] = metric_map[metric]
                log['content'] = metric
                log['name'] = item['label']
                exception_metrics.append(log)
        res_data = {'Exception_categories': exception_metrics}
        response['Result'] = res_data
    except Exception as e:
        response['code'] = 1
        response['message'] = str(e)
    res = make_response(jsonify(response))  # 设置响应体
    res.headers['Access-Control-Allow-Origin'] = "*"  # 设置允许跨域
    res.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    return res


@app.route('/getMetricDetail', methods=['GET', 'POST'])
def getMetricDetail():
    response = deepcopy(result_response)
    try:
        metrics_id = json.loads(request.data).get('metrics_id')
        service_id = json.loads(request.data).get('service_id')
        print(metrics_id)
        print("service_id: " + service_id)
        metrics_link = consAnomalyChain(graph_data, service_id, metrics_id, anomalous_services)
        res_data = {
            'metric_id': metrics_id,
            'content': metric_map_1[metrics_id],
            'service_name': ' '.join([item['label'] for item in anomalous_services if item['id'] == service_id]),
            # 'service_ip': ' '.join([item['ip'] for item in anomalous_services if item['id'] == service_id]),
            'metrics_link': metrics_link
        }
        response['Result'] = res_data
    except Exception as e:
        response['code'] = 1
        response['message'] = str(e)
    res = make_response(jsonify(response))  # 设置响应体
    res.headers['Access-Control-Allow-Origin'] = "*"  # 设置允许跨域
    res.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    return res